#include "actionsettingsdialog.h"
#include "ui_actionsettingsdialog.h"
#include <QDateTime>
#include <QDebug>
#include <QDomDocument>
#include <QHBoxLayout>
#include <QItemSelectionModel>
#include <QMenu>
#include <QPushButton>
#include <QStandardItemModel>
#include <QTableView>
#include <QVBoxLayout>
#include <QUuid>
#include "actioneditdialog.h"
#include "window.h"

ActionSettingsDialog::ActionSettingsDialog(Layout *layout, Action *action, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ActionSettingsDialog)
{
    ui->setupUi(this);

    setupModel();
    setupViews();

    mpLayout = layout;
    mpAction = action;
}

ActionSettingsDialog::~ActionSettingsDialog()
{
    delete ui;
}

void ActionSettingsDialog::done(int r)
{
    Q_UNUSED(r);

    hide();
    //QDialog::done(r);
}

void ActionSettingsDialog::load(QString &xmlData)
{
    mpAction->load(xmlData);

    mpActionModel->removeRows(0, mpActionModel->rowCount());

    for (int i=0; i<mpAction->mTimers.count(); i++) {
        for (int j=0; j<mpLayout->mButtons.count(); j++) {
            if ((mpLayout->mButtons[j].mCId == mpAction->mTimers[i].mCId)
                    && (mpLayout->mButtons[j].mBId == mpAction->mTimers[i].mBId)
                    && (mpLayout->mButtons[j].mRId == mpAction->mTimers[i].mRId)) {
                mpActionModel->insertRows(0, 1);
                mpActionModel->setData(mpActionModel->index(0, ActionName), mpLayout->mButtons[j].mName);

                mpActionModel->setData(mpActionModel->index(0, ActionStartTime), timeString(mpAction->mTimers[i].mStartTime));
                mpActionModel->setData(mpActionModel->index(0, ActionStartAction), actionString(mpAction->mTimers[i].mStartAction));
                mpActionModel->setData(mpActionModel->index(0, ActionEndTime), timeString(mpAction->mTimers[i].mEndTime));
                mpActionModel->setData(mpActionModel->index(0, ActionEndAction), actionString(mpAction->mTimers[i].mEndAction));
                mpActionModel->setData(mpActionModel->index(0, ActionDayOfWeek), mpAction->mTimers[i].mDayOfWeek);

                mpActionModel->setData(mpActionModel->index(0, ActionCid), mpAction->mTimers[i].mCId);
                mpActionModel->setData(mpActionModel->index(0, ActionBid), mpAction->mTimers[i].mBId);
                mpActionModel->setData(mpActionModel->index(0, ActionRid), mpAction->mTimers[i].mRId);
                mpAction->mTimers[i].uuid = QUuid::createUuid().toString();
                mpActionModel->setData(mpActionModel->index(0, ActionUuid), mpAction->mTimers[i].uuid);
                break;
            }
        }
    }
    mpActionModel->sort(ActionName);

    mpActionView->setCurrentIndex(mpActionModel->index(0, ActionName));
}

void ActionSettingsDialog::onButtonUpload()
{
    Window *parent = (Window *)parentWidget();
    parent->onActionSettingsDialogShow(false);
}

void ActionSettingsDialog::onActionShowContextMenu(const QPoint& pos)
{
    QMenu *contextMenu = new QMenu(this);
    contextMenu->addAction(QString::fromUtf8("추가"), this, SLOT(onActionMenuAdd()));
    if (mpActionView->indexAt(pos).isValid()) {
        contextMenu->addSeparator();
        contextMenu->addAction(QString::fromUtf8("수정"), this, SLOT(onActionMenuEdit()));
        contextMenu->addAction(QString::fromUtf8("삭제"), this, SLOT(onActionMenuDel()));
    }
    QPoint pt = pos;
    pt.ry() += mpActionView->horizontalHeader()->height();
    contextMenu->exec(mapToGlobal(pt));
    delete contextMenu;
}

void ActionSettingsDialog::onActionMenuAdd()
{
    RelayTimer rt;
    ActionEditDialog dlg(mpLayout, &rt);
    if (QDialog::Accepted == dlg.exec()) {
        for (int j=0; j<mpLayout->mButtons.count(); j++) {
            if ((mpLayout->mButtons[j].mCId == rt.mCId)
                    && (mpLayout->mButtons[j].mBId == rt.mBId)
                    && (mpLayout->mButtons[j].mRId == rt.mRId)) {
                mpActionModel->insertRows(0, 1);
                mpActionModel->setData(mpActionModel->index(0, ActionName), mpLayout->mButtons[j].mName);

                mpActionModel->setData(mpActionModel->index(0, ActionStartTime), timeString(rt.mStartTime));
                mpActionModel->setData(mpActionModel->index(0, ActionStartAction), actionString(rt.mStartAction));
                mpActionModel->setData(mpActionModel->index(0, ActionEndTime), timeString(rt.mEndTime));
                mpActionModel->setData(mpActionModel->index(0, ActionEndAction), actionString(rt.mEndAction));
                mpActionModel->setData(mpActionModel->index(0, ActionDayOfWeek), rt.mDayOfWeek);

                mpActionModel->setData(mpActionModel->index(0, ActionCid), rt.mCId);
                mpActionModel->setData(mpActionModel->index(0, ActionBid), rt.mBId);
                mpActionModel->setData(mpActionModel->index(0, ActionRid), rt.mRId);
                rt.uuid = QUuid::createUuid().toString();
                mpActionModel->setData(mpActionModel->index(0, ActionUuid), rt.uuid);

                mpActionModel->sort(ActionName);

                mpAction->mTimers.append(rt);
                break;
            }
        }
    }
}

void ActionSettingsDialog::onActionMenuEdit()
{
    if (mpActionView->currentIndex().isValid()) {
        int row = mpActionView->currentIndex().row();
        QString uuid = mpActionModel->index(row, ActionUuid).data().toString();
        for (int i=0; i<mpAction->mTimers.count(); i++) {
            if (mpAction->mTimers[i].uuid == uuid) {
                ActionEditDialog dlg(mpLayout, &mpAction->mTimers[i]);
                if (QDialog::Accepted == dlg.exec()) {
                    mpActionModel->setData(mpActionModel->index(row, ActionStartTime), timeString(mpAction->mTimers[i].mStartTime));
                    mpActionModel->setData(mpActionModel->index(row, ActionStartAction), actionString(mpAction->mTimers[i].mStartAction));
                    mpActionModel->setData(mpActionModel->index(row, ActionEndTime), timeString(mpAction->mTimers[i].mEndTime));
                    mpActionModel->setData(mpActionModel->index(row, ActionEndAction), actionString(mpAction->mTimers[i].mEndAction));
                    mpActionModel->setData(mpActionModel->index(row, ActionDayOfWeek), mpAction->mTimers[i].mDayOfWeek);
                }
                break;
            }
        }
    }
}

void ActionSettingsDialog::onActionMenuDel()
{
    if (mpActionView->currentIndex().isValid()) {
        int row = mpActionView->currentIndex().row();
        QString uuid = mpActionModel->index(row, ActionUuid).data().toString();
        for (int i=0; i<mpAction->mTimers.count(); i++) {
            if (mpAction->mTimers[i].uuid == uuid) {
                mpAction->mTimers.removeAt(i);
                mpActionModel->removeRow(row);
                break;
            }
        }
    }
}

void ActionSettingsDialog::setupModel()
{
    mpActionModel = new QStandardItemModel(0, ActionColumn, this);
    mpActionModel->setHeaderData(ActionName, Qt::Horizontal, tr("name"));
    mpActionModel->setHeaderData(ActionStartTime, Qt::Horizontal, tr("startTime"));
    mpActionModel->setHeaderData(ActionStartAction, Qt::Horizontal, tr("startAction"));
    mpActionModel->setHeaderData(ActionEndTime, Qt::Horizontal, tr("endTime"));
    mpActionModel->setHeaderData(ActionEndAction, Qt::Horizontal, tr("endAction"));
    mpActionModel->setHeaderData(ActionDayOfWeek, Qt::Horizontal, tr("dayOfWeek"));
    mpActionModel->setHeaderData(ActionCid, Qt::Horizontal, tr("cid"));
    mpActionModel->setHeaderData(ActionBid, Qt::Horizontal, tr("bid"));
    mpActionModel->setHeaderData(ActionRid, Qt::Horizontal, tr("rid"));
    mpActionModel->setHeaderData(ActionUuid, Qt::Horizontal, tr("uuid"));
}

void ActionSettingsDialog::setupViews()
{
    mpActionView = new ActionItemView;
    mpActionView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    mpActionView->setSelectionMode(QAbstractItemView::SingleSelection);
    //mpActionView->setSelectionBehavior(QAbstractItemView::SelectRows);
    mpActionView->sortByColumn(ActionName, Qt::AscendingOrder);
    mpActionView->setModel(mpActionModel);
    /*mpActionView->hideColumn(ActionCid);
    mpActionView->hideColumn(ActionBid);
    mpActionView->hideColumn(ActionRid);
    mpActionView->hideColumn(ActionUuid);*/

    mpActionView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(mpActionView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onActionShowContextMenu(const QPoint&)));

    QHeaderView *header = mpActionView->horizontalHeader();
    //headerAction->setResizeMode(QHeaderView::ResizeToContents);
    header->setResizeMode(QHeaderView::Fixed);
    header->resizeSection(ActionName, 90);
    header->resizeSection(ActionStartTime, 75);
    header->resizeSection(ActionStartAction, 75);
    header->resizeSection(ActionEndTime, 75);
    header->resizeSection(ActionEndAction, 75);
    header->resizeSection(ActionDayOfWeek, 75);
    header->resizeSection(ActionCid, 30);
    header->resizeSection(ActionBid, 30);
    header->resizeSection(ActionRid, 30);
    header->resizeSection(ActionUuid, 200);


    QHBoxLayout *hLayout = new QHBoxLayout;
    QPushButton *button;
    button = new QPushButton(QString::fromUtf8("업로드"));
    connect(button, SIGNAL(clicked()), this, SLOT(onButtonUpload()));
    hLayout->addWidget(button);
    button = new QPushButton(QString::fromUtf8("취소"));
    connect(button, SIGNAL(clicked()), this, SLOT(hide()));
    hLayout->addWidget(button);

    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addWidget(mpActionView);
    vLayout->addLayout(hLayout);
    setLayout(vLayout);
}

QString ActionSettingsDialog::timeString(QString time)
{
    if (TIME_SUNRISE_STR == time) {
        return DISP_SUNRISE_STR;
    } else if (TIME_SUNSET_STR == time) {
        return DISP_SUNSET_STR;
    }

    return time;
}

QString ActionSettingsDialog::actionString(int action)
{
    switch (action) {
    case ACTION_OFF:
        return "OFF";
    case ACTION_ON:
        return "ON";
    case ACTION_AIR:
        return QString::fromUtf8("송풍");//AIR";
    case ACTION_COOLING:
        return QString::fromUtf8("냉방");//"COOLING";
    case ACTION_HEATING:
        return QString::fromUtf8("난방");//"HEATING";
    }

    return "UNKNOWN";
}
